<template>
  <view class="uni-container">
    <uni-forms
      ref="form"
      :model="formData"
      validateTrigger="bind"
      label-width="100px"
    >
      <uni-forms-item
        name="user_id"
        label="优惠券所属用户ID"
        v-if="isSuperAdmin"
        required
      >
        <uni-easyinput
          placeholder="优惠券所属用户ID，参考uni-id-users表"
          :disabled="true"
          v-model="formData.user_id"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="category_id" label="优惠券所属活动" required>
        <uni-data-picker
          v-model="formData.category_id"
          collection="news-articles-image"
          :where="titleFormat"
          field="title as text, _id as value"
          @change="onCategoryChange"
        ></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="name" label="优惠券名称" required>
        <uni-easyinput
          placeholder="优惠券名称"
          v-model="formData.name"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="discount" label="折扣率" required>
        <uni-data-select
          v-model="formData.discount"
          :localdata="formOptions.discount_data"
          placeholder="请选择折扣率"
        ></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="validity" label="有效期" required>
        <uni-datetime-picker
          v-model="formData.validity"
          type="time"
          :clear-icon="false"
          return-type="timestamp"
          placeholder="请选择优惠券有效期"
        ></uni-datetime-picker>
        <text class="tips-text"
          >优惠券的有效期自动设置为活动结束当天晚上的12点</text
        >
      </uni-forms-item>
      <uni-forms-item name="status" label="优惠券状态">
        <uni-data-checkbox
          v-model="formData.status"
          :localdata="formOptions.status_localdata"
        ></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="customImage" label="自定义图片">
        <uni-file-picker
          v-model="formData.customImage"
          fileMediatype="image"
          return-type="object"
          :auto-upload="true"
        ></uni-file-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button
          type="primary"
          class="uni-button"
          style="width: 100px"
          @click="submit"
        >
          提交
        </button>
        <navigator open-type="navigateBack" style="margin-left: 15px">
          <button class="uni-button" style="width: 100px">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from "../../js_sdk/validator/coupons.js";
import { store } from "@/uni_modules/uni-id-pages/common/store";

// 删除全局导入
const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = "coupons";

function numberRange(start, end) {
  return Array.from({ length: end - start + 1 }, (_, i) => ({
    value: start + i,
    text: `${start + i}折`,
  }));
}

function getValidator(fields) {
  let result = {};
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key];
    }
  }
  return result;
}

export default {
  data() {
    let formData = {
      category_id: "",
      user_id: "", // 将由计算属性自动填充
      name: "",
      discount: null,
      validity: "",
      status: 0,
      customImage: null,
      create_date: null,
      last_modify_date: null,
    };

    return {
      formData,
      titleFormat: "",
      startDate: Date.now(),
      formOptions: {
        // 添加 formOptions 对象
        discount_data: numberRange(1, 99),
        status_localdata: [
          {
            value: 0,
            text: "未发布",
          },
          {
            value: 1,
            text: "已发布",
          },
          {
            value: 2,
            text: "已过期",
          },
        ],
      },
      rules: {
        ...getValidator(Object.keys(formData)),
      },
    };
  },

  computed: {
    isSuperAdmin() {
      return this.$hasRole("admin");
    },
    userId() {
      if (store.hasLogin) {
        return store.userInfo._id;
      }
      uni.showModal({
        content: "获取用户信息失败，请重新登录",
        showCancel: false,
      });
      return "";
    },
  },

  onLoad() {
    // 组件加载时设置用户ID
    if (store.hasLogin) {
      this.formData.user_id = this.userId;
    }

    // 设置活动过滤条件
    if (this.isSuperAdmin) {
      this.titleFormat = 'title != null && title != ""';
    } else {
      const userId = store.userInfo._id;
      this.titleFormat = `title != null && title != \"\" && user_id == '${userId}'`;
    }
  },

  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  methods: {
    getValidator(fields) {
      let result = {};
      for (let key in validator) {
        if (fields.includes(key)) {
          result[key] = validator[key];
        }
      }
      return result;
    },
    pickerChange(e, name) {
      this.formOptions[name + "_index"] = e.detail.value;
      // 提取数字值并转换为数值类型
      this.formData[name] = parseInt(
        this.formOptions[name + "_data"][e.detail.value]
      );
    },
    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true,
      });
      this.$refs.form
        .validate()
        .then((res) => {
          return this.submitForm(res);
        })
        .catch(() => {})
        .finally(() => {
          uni.hideLoading();
        });
    },

    /**
     * 提交表单
     */
    async submitForm(value) {
      try {
        // 处理图片数据格式
        const submitData = { ...value };
        if (submitData.customImage && submitData.customImage.url) {
          submitData.customImage = submitData.customImage.url;
        }

        // 新增用户ID字段
        if (!submitData.user_id) {
          submitData.user_id = this.userId;
        }

        // 在方法内部导入云对象
        const couponManager = uniCloud.importObject("coupon-manager", {
          customUI: true, // 使用自定义界面
        });
        const res = await couponManager.addCoupon(submitData);

        if (res.code === 200) {
          uni.showToast({
            title: "新增成功",
          });
          this.getOpenerEventChannel().emit("refreshData");
          setTimeout(() => uni.navigateBack(), 500);
        } else {
          uni.showModal({
            content: res.message || "添加失败",
            showCancel: false,
          });
        }
      } catch (err) {
        uni.showModal({
          content: err.message || "请求服务失败",
          showCancel: false,
        });
      }
    },
    async onCategoryChange(e) {
      const articleId = e.detail.value[0].value;

      try {
        const db = uniCloud.database();
        const res = await db
          .collection("news-articles-image")
          .doc(articleId)
          .field("end_time")
          .get();

        if (res.result.data && res.result.data.length > 0) {
          const endTime = res.result.data[0].end_time;
          const endDate = new Date(endTime);
          // 设置为当天的 23:59:59.999
          endDate.setHours(23, 59, 59, 999);

          // 设置优惠券的有效期
          this.formData.validity = endDate.getTime();
        }
      } catch (err) {
        console.error("获取活动结束时间失败：", err);
        uni.showToast({
          title: "获取活动信息失败",
          icon: "none",
        });
      }
    },
  },
};
</script>
<style>
.tips-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  display: block;
}
</style>
